package com.nus.servlets;

import com.nus.beans.Project;
import com.nus.beans.ProjectStatus;
import com.nus.beans.User;
import com.nus.database.ProjectsDBManager;
import com.nus.services.ConversionService;
import com.nus.services.FilteringService;
import com.nus.services.ValidationService;
import org.apache.log4j.Logger;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.util.*;

/**
 * Created by IntelliJ IDEA.
 * User: dell
 * Date: 9/28/12
 * Time: 9:23 PM
 * To change this template use File | Settings | File Templates.
 */
public class UpdateProjectServlet extends AbstractServlet {
    private Logger logger = Logger.getLogger(this.getClass());

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        String projectName = request.getParameter("projectName");
        String startYear = request.getParameter("startYear");
        String startMonth = request.getParameter("startMonth");
        String startDate = request.getParameter("startDate");
        String endYear = request.getParameter("endYear");
        String endMonth = request.getParameter("endMonth");
        String endDate = request.getParameter("endDate");
        String deadlineYear = request.getParameter("deadlineYear");
        String deadlineMonth = request.getParameter("deadlineMonth");
        String deadlineDate = request.getParameter("deadlineDate");
        String projectStatus = request.getParameter("projectStatus");
        String projectIdStr = request.getParameter("id");

        ValidationService validationService = new ValidationService();
        ConversionService conversionService = new ConversionService();
        String errorMessage;

        String nextPage = "loadUpdateProject.do";


        request.setAttribute("projects", projectIdStr);

        if (validationService.isEmpty(projectName)) {
            errorMessage = "Project name should not be empty";
            logger.error(errorMessage);
        } else if (validationService.isEmpty(projectStatus)) {
            errorMessage = "Project stauts should not be empty";
            logger.error(errorMessage);
        } else if (validationService.isEmpty(startYear) || validationService.isEmpty(startMonth) || validationService.isEmpty(startDate)) {
            errorMessage = "Start date should not be empty";
            logger.error(errorMessage);
        } else if (validationService.isEmpty(endYear) || validationService.isEmpty(endMonth) || validationService.isEmpty(endDate)) {
            errorMessage = "End date should not be empty";
            logger.error(errorMessage);
        } else if (validationService.isEmpty(deadlineYear) || validationService.isEmpty(deadlineMonth) || validationService.isEmpty(deadlineDate)) {
            errorMessage = "Deadline date should not be empty";
            logger.error(errorMessage);
        } else {

            Date startDateActual = conversionService.getDate(startYear, startMonth, startDate);
            Date endDateActual = conversionService.getDate(endYear, endMonth, endDate);
            Date deadlineDateActual = conversionService.getDate(deadlineYear, deadlineMonth, deadlineDate);

            if (startDateActual == null) {
                errorMessage = "Invalid value entered for start date";
            } else if (endDateActual == null) {
                errorMessage = "Invalid value entered for end date";
            } else if (deadlineDate == null) {
                errorMessage = "Invalid value entered for deadline date";
            } else if (startDateActual.after(endDateActual)) {
                errorMessage = "Invalid input. End date should be later than start date";
            } else if (startDateActual.after(deadlineDateActual)) {
                errorMessage = "Invalid input. Deadline date should be later than start date";
            } else {


                Project project = new Project();
                int projectId = Integer.parseInt(projectIdStr);
                project.setId(projectId);
                project.setProjectName(projectName);
                project.setStatus(ProjectStatus.valueOf(projectStatus));
                project.setStartingDate(startDateActual);
                project.setEstimatedEndDate(endDateActual);
                project.setDeadline(deadlineDateActual);

                List<Integer> newUsers = new ArrayList<Integer>();
                Enumeration e = request.getParameterNames();
                String tmpUserId;
                while (e.hasMoreElements()) {
                    String parameter = String.valueOf(e.nextElement());
                    if (parameter.startsWith("user_")) {
                        tmpUserId = parameter.substring(parameter.indexOf("_") + 1);
                        newUsers.add(Integer.parseInt(tmpUserId));
                    }
                }

                Connection connection = getUserDatabaseConnection(request);
                ProjectsDBManager projectsDBManager = new ProjectsDBManager(connection);

                List<User> existingAssigneesList = projectsDBManager.getProjectAssigneesList(projectId);
                FilteringService filteringService = new FilteringService();
                List<User> usersToAdd = filteringService.getUsersToAdd(existingAssigneesList, newUsers);
                List<User> usersToDelete = filteringService.getUsersToDelete(existingAssigneesList, newUsers);

                projectsDBManager.updateProject(project, usersToAdd, usersToDelete);

                projectsDBManager.close();
                nextPage = "viewProjects.do";
                errorMessage = "Project successfully updated.";
            }

        }

        RequestDispatcher requestDispatcher = request.getRequestDispatcher(nextPage);
        request.setAttribute("ERROR_MESSAGE", errorMessage);
        requestDispatcher.forward(request, response);
    }
}
